package tk

import (
	"bytes"
	"github.com/bytedance/sonic"
	"io"
	"net/http"
	"strings"
)

// GetAccessToken 获取access_token
func GetAccessToken(appid, appsecret string) (string, error) {
	url := "https://developer.toutiao.com/api/apps/v2/token"
	requestData := map[string]string{
		"appid":      appid,
		"secret":     appsecret,
		"grant_type": "client_credential",
	}

	requestBody, _ := sonic.Marshal(requestData)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", "application/sonic")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	var result AccessTokenRes
	err = sonic.Unmarshal(data, &result)
	if err != nil && result.ErrNo != 0 {
		return "", err
	}
	return result.Data.AccessToken, nil
}

// GetRoomInfo 获取直播间信息
func GetRoomInfo(token, accessToken string) GetRoomInfoRes {
	client := &http.Client{}
	var data = strings.NewReader(`{"token":"` + token + `"}`)
	req, err := http.NewRequest("POST", "https://webcast.bytedance.com/api/webcastmate/info", data)
	if err != nil {
		return GetRoomInfoRes{}
	}
	req.Header.Set("X-Token", accessToken)
	req.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return GetRoomInfoRes{}
	}
	defer resp.Body.Close()
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		return GetRoomInfoRes{}
	}
	var roomInfo GetRoomInfoRes
	err = sonic.Unmarshal(bodyText, &roomInfo)
	if err != nil {
		return GetRoomInfoRes{}
	}
	return roomInfo
}

//"直播间消息类型，需要前置申请开通了对应类型直播间数据能力才可以调用。
//1. 评论：live_comment
//2. 礼物：live_gift
//3. 点赞：live_like"
//4. 粉丝团：live_fansclub

// StartRoom 启动直播间推送任务
func StartRoom(roomId, appid, msgType, accessToken string) (StartRoomRes, error) {
	url := "https://webcast.bytedance.com/api/live_data/task/start"
	requestData := map[string]string{
		"roomid":   roomId,
		"appid":    appid,
		"msg_type": msgType,
	}
	payload, _ := sonic.Marshal(requestData)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
	req.Header.Set("access-token", accessToken)
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return StartRoomRes{}, err
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)
	var result StartRoomRes
	err = sonic.Unmarshal(data, &result)
	if err != nil {
		return StartRoomRes{}, err
	}
	return result, nil
}

// StopRoom 停止直播间推送任务
func StopRoom(roomId, appid, msgType, accessToken string) (StopRoomRes, error) {
	url := "https://webcast.bytedance.com/api/live_data/task/stop"
	requestData := map[string]string{
		"roomid":   roomId,
		"appid":    appid,
		"msg_type": msgType,
	}
	payload, _ := sonic.Marshal(requestData)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
	req.Header.Set("access-token", accessToken)
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return StopRoomRes{}, err
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)
	var result StopRoomRes
	err = sonic.Unmarshal(data, &result)
	if err != nil {
		return StopRoomRes{}, err
	}
	return result, nil
}

// GetTask 查询任务状态
func GetTask(roomId, appid, msgType, accessToken string) (GetTaskRes, error) {
	url := "https://webcast.bytedance.com/api/live_data/task/get"
	requestData := map[string]string{
		"roomid":   roomId,
		"appid":    appid,
		"msg_type": msgType,
	}
	payload, _ := sonic.Marshal(requestData)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
	req.Header.Set("access-token", accessToken)
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return GetTaskRes{}, err
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)
	var result GetTaskRes
	err = sonic.Unmarshal(data, &result)
	if err != nil {
		return GetTaskRes{}, err
	}
	return result, nil
}

// 礼物置顶
func GiftTop(roomId, appid, accessToken string, giftList []string) (GiftTopRes, error) {
	url := "https://webcast.bytedance.com/api/gift/top_gift"
	requestData := map[string]interface{}{
		"roomid":           roomId,
		"appid":            appid,
		"sec_gift_id_list": giftList,
	}
	payload, _ := sonic.Marshal(requestData)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
	req.Header.Set("access-token", accessToken)
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return GiftTopRes{}, err
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)
	var result GiftTopRes
	err = sonic.Unmarshal(data, &result)
	if err != nil {
		return GiftTopRes{}, err
	}
	return result, nil
}

// HandlerChatMessage 解析评论消息
func HandlerChatMessage(msg []byte) ChatMessage {
	var chatMessage ChatMessage
	err := sonic.Unmarshal(msg, &chatMessage)
	if err != nil {
		return ChatMessage{}
	}
	return chatMessage
}

// HandlerGiftMessage 解析评论消息
func HandlerGiftMessage(msg []byte) GiftMessage {
	var giftMessage GiftMessage
	err := sonic.Unmarshal(msg, &giftMessage)
	if err != nil {
		return GiftMessage{}
	}
	return giftMessage
}

// HandlerLikeMessage 解析评论消息
func HandlerLikeMessage(msg []byte) LikeMessage {
	var likeMessage LikeMessage
	err := sonic.Unmarshal(msg, &likeMessage)
	if err != nil {
		return LikeMessage{}
	}
	return likeMessage
}

// HandlerFansMessage 解析评论消息
func HandlerFansMessage(msg []byte) FansMessage {
	var fansMessage FansMessage
	err := sonic.Unmarshal(msg, &fansMessage)
	if err != nil {
		return FansMessage{}
	}
	return fansMessage
}
